package com.ruoyi.web.controller.epidemic;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.epidemic.domain.EpidemicControlDept;
import com.ruoyi.epidemic.service.IEpidemicControlDeptService;
import com.ruoyi.epidemic.service.QRCodeService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * 疫情防控部门管理
 */
@Controller
@RequestMapping("/epidemic/dept")
public class EpidemicDeptController extends BaseController {

    private String prefix = "epidemic/dept/epidemic";

    @Autowired
    private IEpidemicControlDeptService epidemicControlDeptService;

    @Autowired
    private QRCodeService qrCodeService;
    /**
     * 加载疫情防控部门树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztreeList = epidemicControlDeptService.selectEpidemicDeptTree(new EpidemicControlDept());
        return ztreeList;
    }

    /**
     * 选择原始疫情防控部门树
     *
     * @param deptId 部门ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = { "/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}" })
    public String selectDeptTree(@PathVariable("deptId") Long deptId, @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
    {
        mmap.put("dept", epidemicControlDeptService.selectEpidemicControlDeptByDeptId(deptId));
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    @RequiresPermissions("epidemic:dept:view")
    @GetMapping()
    public String dept()
    {
        return prefix + "/dept";
    }

    @RequiresPermissions("epidemic:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<EpidemicControlDept> list(EpidemicControlDept dept)
    {
        List<EpidemicControlDept> deptList = epidemicControlDeptService.selectEpidemicControlDeptList(dept);
        return deptList;
    }

    /**
     * 新增疫情防控部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        mmap.put("dept", epidemicControlDeptService.selectDeptById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存疫情防控部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("epidemic:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated EpidemicControlDept dept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(epidemicControlDeptService.checkDeptNameUnique(dept)))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getLoginName());
        return toAjax(epidemicControlDeptService.insertEpidemicControlDept(dept));
    }

    /**
     * 修改疫情防控部门
     */
    @RequiresPermissions("epidemic:dept:edit")
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap)
    {
        EpidemicControlDept dept = epidemicControlDeptService.selectDeptById(deptId);
        if (StringUtils.isNotNull(dept) && 1L == deptId)
        {
            dept.setParentName("无");
        }
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 修改保存疫情防控部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("epidemic:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated EpidemicControlDept dept)
    {
        Long deptId = dept.getDeptId();

        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(epidemicControlDeptService.checkDeptNameUnique(dept)))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && epidemicControlDeptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getLoginName());
        return toAjax(epidemicControlDeptService.updateEpidemicControlDept(dept));
    }

    /**
     * 删除疫情防控部门
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("epidemic:dept:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId)
    {
        if (epidemicControlDeptService.selectDeptCount(deptId) > 0)
        {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (epidemicControlDeptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(epidemicControlDeptService.deleteEpidemicControlDeptByDeptId(deptId));
    }

    /**
     * 校验疫情防控部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(EpidemicControlDept dept)
    {
        return epidemicControlDeptService.checkDeptNameUnique(dept);
    }


    /**
     * 选择疫情防控部门树
     *
     */
    @GetMapping(value = { "/selectDeptTree/checkBox" })
    public String selectDeptTreeCheckBox(ModelMap mmap)
    {
        return prefix + "/treeCheckBox";
    }

    @GetMapping(value = { "/showQR/{deptId}" })
    public String showQRcode(@PathVariable("deptId") Long deptId,Model model) {
    	//判断是否是叶子节点
    	if (epidemicControlDeptService.selectDeptCount(deptId) > 0)
        {
    		model.addAttribute("msg", "该部门不是最小审核单位，不能生成二维码");
    		model.addAttribute("code", "1");
        }else {
        	model.addAttribute("code", "0");
        	EpidemicControlDept dept = epidemicControlDeptService.selectDeptById(deptId);
        	model.addAttribute("dept", dept);
        	
        }
    	
    	return prefix + "/qrcode";
    }
    @GetMapping(value = { "/showQRcodeImg/{deptId}" })
    public void showQRcodeImg(@PathVariable("deptId") Long deptId,Model model, HttpServletResponse response) {
    	//判断是否是叶子节点
    	if (epidemicControlDeptService.selectDeptCount(deptId) > 0)
        {
    		model.addAttribute("msg", "该部门不是最小审核单位，不能生成二维码");
    		model.addAttribute("code", "1");
        }else {
        	model.addAttribute("code", "0");
        	EpidemicControlDept dept = epidemicControlDeptService.selectDeptById(deptId);
        	String outside=dept.getOutside();
        	String codeContent="";
        	if("Y".equals(outside)) {
        		  codeContent="http://fangkong.hfmri.net:18080/wb/epidemic/collect/add/"+deptId;
        	}else {
        		codeContent="http://fangkong.hfmri.net:18080/wxcp/epidemic/collect/check/?deptId="+deptId;
        	}
        	
        	qrCodeService.createQRCode2Stream(codeContent, response);
        }
    	
    	 
    }
    

}
